import { MonitorOptions } from './types';
import { Reporter } from './core/reporter';
import { ErrorMonitor } from './core/errorMonitor';
import { PerformanceMonitor } from './core/performanceMonitor';
import { BehaviorMonitor } from './core/behaviorMonitor';

export default class MonitorSDK {
  private reporter: Reporter;
  private errorMonitor?: ErrorMonitor;
  private performanceMonitor?: PerformanceMonitor;
  private behaviorMonitor?: BehaviorMonitor;

  constructor(options: MonitorOptions) {
    // 校验必填参数
    if (!options.reportUrl) {
      throw new Error('请配置上报接口URL（reportUrl）');
    }

    // 初始化上报器
    this.reporter = new Reporter(options);

    // 按需初始化监控模块
    if (options.enableError !== false) {
      this.errorMonitor = new ErrorMonitor(this.reporter);
    }

    if (options.enablePerformance !== false) {
      this.performanceMonitor = new PerformanceMonitor(this.reporter);
    }

    if (options.enableBehavior !== false) {
      this.behaviorMonitor = new BehaviorMonitor(this.reporter);
    }
  }

  /**
   * 手动上报错误
   */
  reportError(error: Error | string) {
    if (!this.errorMonitor) return;

    const message = error instanceof Error ? error.message : String(error);
    const stack = error instanceof Error ? error.stack || '' : '';

    this.reporter.push({
      type: 'error',
      subType: 'js_error',
      message,
      stack
    });
  }

  /**
   * 手动上报HTTP请求错误
   */
  reportHttpError(url: string, method: string, status: number, error: string) {
    this.errorMonitor?.listenHttpError()(url, method, status, error);
  }

  /**
   * 手动上报行为
   */
  track(action: string, data?: Record<string, any>) {
    this.behaviorMonitor?.track(action, data);
  }

  /**
   * 开启点击行为自动追踪
   */
  enableAutoTrackClick() {
    this.behaviorMonitor?.autoTrackClick();
  }
}

// 导出类型定义（供TypeScript用户）
export * from './types';